package particles;
import flash.display.BitmapData;
import flash.display.Graphics;
import flash.geom.Point;
import flash.geom.Rectangle;
import haxe.io.Bytes;

/**
 * ...
 * @author 
 */

class Particle 
{
	public var x: Float;
	public var y: Float;
	public var dx: Float;
	public var dy: Float;
	public var dgx: Float;
	public var dgy: Float;
	
	public var radius: Float;
	public var dr: Float;

	public var alpha: Float;
	public var da: Float;
	
	public var color: UInt;
	var r1: Int; var g1: Int; var b1: Int;
	var r2: Int; var g2: Int; var b2: Int;

	public var lifeTime: Int;
	public var maxLifeTime: Int;
	
	public var trail: Int;
	private var trails: Array<Point>;

	
	public function new() 
	{
		x = y = 0;
		dx = dy = 0;
		dgx = dgy = 0;
		radius = 2;
		dr = 0;
		alpha = 1;
		da = 0;
		color = 0xffffff;
		maxLifeTime = lifeTime = 1;
		trail = 0;
		trails = new Array<Point>();
	}	
	
	
	public function SetColors(c1: UInt, c2: UInt)
	{
		color = c1;
		r1 = c1 & 0xff;
		g1 = (c1 >> 8) & 0xff;
		b1 = (c1 >> 16) & 0xff;
		r2 = c2 & 0xff;
		g2 = (c2 >> 8) & 0xff;
		b2 = (c2 >> 16) & 0xff;
	}
	
	
	public function Draw(xpos: Float, ypos: Float, g: BitmapData)
	{
		var alphaColor: UInt = (Math.ceil(0xff * alpha) << 24) | (color & 0x00ffffff);
		
		g.fillRect(new Rectangle(xpos+x-radius, ypos+y-radius, radius*2, radius*2), alphaColor);
		
		if (trails.length > 0) {
			var alpha2 = alpha;
			for (p in trails) {
				alpha2 /= 1.2;
				alphaColor = (Math.ceil(0xff * alpha) << 24) | (color & 0x00ffffff);
				g.fillRect(new Rectangle(xpos+p.x - radius, ypos+p.y - radius, radius * 2, radius * 2), alphaColor);
			}
		}
	}
	
	
	public function Update()
	{
		var p: Float = maxLifeTime - lifeTime;
		p /= maxLifeTime;
		
		//trace(p);

		x += dx;
		y += dy;
		
		dx += dgx;
		dy += dgy;
		
		var r: Int = Math.ceil((r2 - r1) * p + r1);
		var g: Int = Math.ceil((g2 - g1) * p + g1);
		var b: Int = Math.ceil((b2 - b1) * p + b1);
		color = (r << 16) | (g << 8) | b;
		
		alpha += da;
		if (alpha > 1) alpha = 1;
		else if (alpha < 0) alpha = 0;
		
		radius += dr;
		if (radius < 0.1) radius = 0.1;
		
		if (trail > 0) {
			trails.push(new Point(x, y));
			if (trails.length > trail) {
				trails.shift();
			}
		}
	}
}
